<?php

namespace epay;

use GuzzleHttp\Client;

class CodePay
{
    protected array $config = [];

    protected string $apiUrl = 'https://qn.exeaaa.com/pay/apisubmit';

    public function __construct(array $config)
    {
        if (!empty($config['url'])) {
            $this->apiUrl = $config['url'] . '/pay/apisubmit';
        }

        $this->config = $config;
    }

    public function submitOrder($order = [])
    {
        if ($order['type'] == 'wechat')
        {
            $order['type'] = 'wxpay';
        }

        $data = [
            'pid' => $this->config['pid'],
            'type' => $order['type'],
            'out_trade_no' => $order['out_trade_no'],
            'notify_url' => $this->config['notify_url'],
            'return_url' => $this->config['return_url'],
            'name' => $order['name'],
            'money' => $order['money'],
            'sign_type' => 'MD5',
        ];

        // 签名
        $data['sign'] = $this->getSign($data);
        try {
            // 发送请求
            $client = new Client();
            $response = $client->request('POST', $this->apiUrl, [
                'form_params' => $data,
                'verify' => false
            ]);
            $body = $response->getBody();
            $result = json_decode($body, true);
        } catch (\Exception $e) {
            $result = ['code' => 0, 'msg' => '请求失败'];
        }
        return $result;
    }


    public function getSign($param){
        ksort($param);
        reset($param);
        $signstr = '';

        foreach($param as $k => $v){
            if($k != "sign" && $k != "sign_type" && $v!=''){
                $signstr .= $k.'='.$v.'&';
            }
        }
        $signstr = substr($signstr,0,-1);
        $signstr .= $this->config['key'];
        $sign = md5($signstr);
        return $sign;
    }


    public function verify(){
        if(empty($_GET)) return false;

        $sign = $this->getSign($_GET);

        if($sign === $_GET['sign']){
            $signResult = true;
        }else{
            $signResult = false;
        }

        return $signResult;
    }
}